package org.ajc.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.ajc.gift.constants.UserConstants;
import org.ajc.gift.domain.User;
import org.ajc.gift.exception.BusinessException;
import org.ajc.gift.exception.ResponseCode;
import org.ajc.gift.exception.RonghuaAssert;
import org.ajc.gift.service.IUserService;
import org.ajc.gift.service.IVerifyCodeService;
import org.ajc.gift.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void registerSendSms(String phone) {
        //1.校验手机是否注册 -- 前端校验不可靠
        User user = userService.selectOne(new EntityWrapper<User>().eq("phone", phone));
        RonghuaAssert.isNull(user, ResponseCode.RESPONSE_CODE_400005);
        //2.给用户发送验证码
        //2.1生成一个验证码
        String code = VerifyCodeUtils.generateVerifyCode(6, "0123456789");
        String key = UserConstants.USER_REGISTER_SEND_SMS_KEY + "-"+phone;
        Object codeInRedis = redisTemplate.opsForValue().get(key);
        if (codeInRedis!=null){//证明当前的手机号已经发过验证码 ,还没有过期
            //1.使用当前的时间-上一次发送的时间<60s 就是不合法的请求--报错
            String codeInRedisStr = codeInRedis.toString();
            code = codeInRedisStr.split(":")[0];
            Long preTime = Long.valueOf(codeInRedisStr.split(":")[1]);
            if(System.currentTimeMillis()-preTime<60*1000){
                throw  new BusinessException(ResponseCode.RESPONSE_CODE_400008);
            }
            // 如果过了重发时间,就要将这个验证码重新再发一遍
        }

        //3.发送到用户的手机
        //SendSmsUtils.sendMsg(phone,code);
        System.out.println("手机验证码为:"+code);
        //4.把手号存储起来--后续在提交数据,保存用户的时候 验证
        redisTemplate.opsForValue().set(key,code+":"+System.currentTimeMillis(),5, TimeUnit.MINUTES);
    }
}
